package com.epic.followup.service.wechat.impl;

import java.util.Optional;

import com.alibaba.fastjson.JSONObject;
import com.epic.followup.model.app.PatientBodyInformationModel;
import com.epic.followup.repository.app.PatientBodyInformationRepository;
import com.epic.followup.service.wechat.WechatPatientBodyInformationService;
import com.epic.followup.temporary.DealMessageResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WechatPatientBodyInformationServiceImpl implements WechatPatientBodyInformationService {

    @Autowired
    private PatientBodyInformationRepository patientBodyInformationRepository;

    @Override
    public DealMessageResponse saveorupdateInformation(Long id, JSONObject information){
        DealMessageResponse res=new DealMessageResponse();
        Optional<PatientBodyInformationModel> ou = patientBodyInformationRepository.findByTimeAndPid(information.getString("datetime"), id);
        if (!ou.isPresent()) {
            PatientBodyInformationModel bi = new PatientBodyInformationModel();
            bi.setAppetite(information.getString("appetite"));
            bi.setTime(information.getString("datetime"));
            bi.setPain(information.getString("pain"));
            bi.setSleep(information.getString("sleep"));
            bi.setWeight(information.getFloat("weight"));
            bi.setPid(id);
            patientBodyInformationRepository.save(bi);
            res.setErrorCode(200);
            res.setErrorMsg("插入成功");
            return res;
        }else{
            PatientBodyInformationModel p=ou.get();
            p.setAppetite(information.getString("appetite"));
            p.setPain(information.getString("pain"));
            p.setSleep(information.getString("sleep"));
            p.setWeight(information.getFloat("weight"));
            patientBodyInformationRepository.save(p);
            res.setErrorCode(200);
            res.setErrorMsg("更新成功");
            return res;
        }
    }

    @Override
    public JSONObject retrieveInformation(Long id,JSONObject information){
        Optional<PatientBodyInformationModel> ou = patientBodyInformationRepository.findByTimeAndPid(information.getString("datetime"), id);
        JSONObject res=new JSONObject();
        if (!ou.isPresent()) {
            res.put("errorCode",502);
            res.put("errorMsg","未查找到信息");
        }else{
            PatientBodyInformationModel p=ou.get();
            res.put("errorCode",200);
            res.put("errorMsg","查找成功");
            res.put("pain",p.getPain());
            res.put("appetite",p.getAppetite());
            res.put("sleep",p.getSleep());
            res.put("weight",p.getWeight());

        }
        return res;
    }





}
